import { ref, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import type { SSEMessage, SSEStatus, SSEOptions } from '@/types'

export function useSSE<T>(options: SSEOptions) {
  const status: Ref<SSEStatus> = ref('CONNECTING')
  const message: Ref<SSEMessage<T> | null> = ref(null)
  const error: Ref<Event | null> = ref(null)
  const eventSource: Ref<EventSource | null> = ref(null)
  let retryTimer: number | null = null
  let lastActivity = Date.now()

  // 默认配置
  const config = {
    autoConnect: true,
    withCredentials: false,
    retryInterval: 5000,
    heartbeatInterval: 30000,
    ...options
  }

  // 心跳检测
  const startHeartbeatCheck = () => {
    const check = () => {
      if (Date.now() - lastActivity > config.heartbeatInterval) {
        console.warn('[SSE] Heartbeat timeout, reconnecting...')
        reconnect()
      }
    }
    const timer = setInterval(check, config.heartbeatInterval)
    onUnmounted(() => clearInterval(timer))
  }

  // 消息处理器
  const handleMessage = (event: MessageEvent) => {
    lastActivity = Date.now()
    try {
      message.value = {
        id: event.lastEventId,
        event: event.type,
        data: JSON.parse(event.data),
        timestamp: Date.now()
      }
    } catch (err) {
      console.error('[SSE] Message parse error:', err)
    }
  }

  // 建立连接
  const connect = () => {
    cleanup()
    status.value = 'CONNECTING'
    
    eventSource.value = new EventSource(config.url, {
      withCredentials: config.withCredentials
    })

    eventSource.value.onopen = () => {
      status.value = 'OPEN'
      lastActivity = Date.now()
    }

    // eventSource.value.addEventListener('HEARTBEAT', (event) => {
    //   lastActivity = Date.now()
    //   try {
    //     message.value = {
    //       id: event.lastEventId,
    //       event: event.type,
    //       data: event.data,
    //       timestamp: Date.now()
    //     }
    //   } catch (err) {
    //     console.error('[SSE] Message parse error:', err)
    //   }
    // })

    eventSource.value.addEventListener('amazon_job_starting', (event) => {
      lastActivity = Date.now()
      try {
        message.value = {
          id: event.lastEventId,
          event: event.type,
          data: event.data,
          timestamp: Date.now()
        }
      } catch (err) {
        console.error('[SSE] Message parse error:', err)
      }
    })

    eventSource.value.addEventListener('amazon_job_exception', (event) => {
      lastActivity = Date.now()
      try {
        message.value = {
          id: event.lastEventId,
          event: event.type,
          data: event.data,
          timestamp: Date.now()
        }
      } catch (err) {
        console.error('[SSE] Message parse error:', err)
      }
    })

    eventSource.value.onerror = (err) => {
      status.value = 'ERROR'
      error.value = err
      reconnect()
    }

    startHeartbeatCheck()
  }

  // 重新连接
  const reconnect = () => {
    if (retryTimer) return
    status.value = 'CONNECTING'
    
    retryTimer = window.setTimeout(() => {
      connect()
      retryTimer = null
    }, config.retryInterval)
  }

  // 清理资源
  const cleanup = () => {
    eventSource.value?.close()
    if (retryTimer) {
      clearTimeout(retryTimer)
      retryTimer = null
    }
  }

  // 初始化
  if (config.autoConnect) {
    connect()
  }

  onUnmounted(() => {
    cleanup()
    status.value = 'CLOSED'
  })

  return {
    status,
    message,
    error,
    connect,
    disconnect: cleanup
  }
}